package com.sz.sidi.oa.ui.login;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Text;

import com.sz.sidi.entity.TuserInfo;
import com.sz.sidi.oa.config.OasidiServer;
import com.sz.sidi.service.IBaseService;

import util.Assert;
import util.DataSource;
import util.Session;


/**
 * 登陆面板
 * 
 */
public class LoginComposite extends Composite {
	
	private Composite parent;


	private static final String DEFAULT_SERVER_URL = "http://127.0.0.1:8080"; //$NON-NLS-1$

	private final static int F_LABEL_HORIZONTAL_INDENT = 210;

	private final static int F_BUTTON_WIDTH_HINT = 50;

	private final static int F_TEXT_WIDTH_HINT = 150;

	private final static int F_COLUMN_COUNT = 4;

	private Composite comp_Login;

	private Text txt_fusername;// 用户名输入框

	private Text txt_fpassword;// 密码输入框

	private Button btn_ok;// 登录按钮

	private Button btn_cancel;// 取消按钮

	private Button btn_set;// 设置按钮

	private boolean isAuthenticated;// 验证是否通过

	private boolean isFinished;// 是否完成

	private ProgressBar progressBar;// 进度条

	private String validateMsg;// 验证消息

	private StackLayout stackLayout;

	private Composite comp_blank;

	private Composite comp_root;

	private Label lab_name;
	private Text txt_name;

	private Label lab_tip;


	public LoginComposite(Composite parent, int style) {
		super(parent, style);
		this.parent = parent;
		comp_Login = null;
		txt_fusername = null;
		txt_fpassword = null;
		btn_ok = null;
		btn_cancel = null;
		isAuthenticated = false;
		isFinished = false;
		init(parent);
	}

	public void init(Composite parent) {
		configureUISplash();
		createUI();
		createUIListeners();
		initCaLogin();
		noPasswordLogin();
	}
	
	/**
	 * 南川平台调用  如果返回用户id不需要输入密码 直接进入欢迎界面
	 */
	private void noPasswordLogin(){}

	private void initCaLogin() {}

	/**
	 * 
	 */
	private void createUIListeners() {
		// Create the OK button listeners
		createUIListenersButtonOK();
		// Create the cancel button listeners
		createUIListenersButtonCancel();
	}

	/**
	 * 
	 */
	private void createUIListenersButtonCancel() {
		btn_cancel.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				handleButtonCancelWidgetSelected();
			}
		});
	}

	/**
	 * 
	 */
	private void handleButtonCancelWidgetSelected() {
		// Abort the loading of the RCP application
		parent.getDisplay().close();
		System.exit(0);
	}

	/**
	 * 
	 */
	private void createUIListenersButtonOK() {
		btn_ok.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				handleButtonOKWidgetSelected();
			}
		});
	}

	private void load() {
		if (isAuthenticated) {
			lab_tip.setForeground(Display.getDefault().getSystemColor(
					SWT.COLOR_DARK_GREEN));
			lab_tip.setText("登录成功，开始加载数据......"); //$NON-NLS-1$

			progressBar.setVisible(true);
			for (final int[] i = { 0 }; i[0] < Session.getInitCount(); i[0]++) {
				lab_tip.setForeground(Display.getDefault().getSystemColor(
						SWT.COLOR_DARK_GREEN));
				lab_tip.setText(Session.getInitTitle(i[0]));
				Session.initSystem(i[0]);
				progressBar.setSelection(i[0]);
			}
			isFinished = true;
		}
	}

	/** 判断验证用户名和密码 */
	private boolean checkValid() {
		if(txt_fpassword.getText().trim()!=null && !txt_fpassword.getText().trim().equals("")
		&& txt_fusername.getText().trim()!=null && !txt_fusername.getText().trim().equals("")		
		){
			String fgh = txt_fusername.getText().trim();
			String psw = txt_fpassword.getText().trim();
			TuserInfo user = Session.checkUser(fgh,psw);
			if(user!=null){
				Session.setUserinfo(user);
				return true;
			}else{
				lab_tip.setForeground(Display.getDefault()
						.getSystemColor(SWT.COLOR_RED));
				lab_tip.setText("密码不正确！"); //$NON-NLS-1$
				txt_fpassword.setFocus();
				return false;
			}
			
		}
		return false;
	}

	/**
	 * 
	 */
	private void handleButtonOKWidgetSelected() {
		if(checkValid()){
			isAuthenticated = true;
			load();
		}else{
			lab_tip.setForeground(Display.getDefault()
					.getSystemColor(SWT.COLOR_RED));
			lab_tip.setText("密码不正确！"); //$NON-NLS-1$
			txt_fpassword.setFocus();
			return;
		}
	}

	/**
	 * 
	 */
	private void createUI() {
		// Create the login panel
		createUICompositeLogin();
		// Create the blank spanner
		createUICompositeBlank();

		createUILabelTip();

		// Create the user name label
		createUILabelUserName();
		// Create the user name text widget
		createUITextUserName();

		createUILableName();

		createUITxtName();
		// Create the password label
		createUILabelPassword();
		// Create the password text widget
		createUITextPassword();
		// Create the blank label
		createUILabelBlank();
		// Create the OK button

		createUIButtonOK();
		// Create the cancel button
		createUIButtonCancel();

		createUIButtonSet();

		txt_fusername.setFocus();
	}

	private void createUITxtName() {
		txt_name = new Text(comp_Login, SWT.BORDER);
		txt_name.setEditable(false);
		 
		// Configure layout data
		GridData data = new GridData(SWT.NONE, SWT.NONE, false, false);
		data.widthHint = F_TEXT_WIDTH_HINT;
		data.horizontalSpan = 3;
		txt_name.setLayoutData(data);
	}

	private void createUILableName() {
		lab_name = new Label(comp_Login, SWT.NONE);
		lab_name.setText("姓 名："); // NON-NLS-1 //$NON-NLS-1$
		// Configure layout data
		GridData data1 = new GridData();
		data1.horizontalIndent = F_LABEL_HORIZONTAL_INDENT;
		lab_name.setLayoutData(data1);
	}

	/**
	 * 
	 */
	private void createUIButtonSet() {}

	/**
	 * 
	 */
	private void createUIButtonCancel() {
		// Create the button
		btn_cancel = new Button(comp_Login, SWT.PUSH);
		btn_cancel.setText("取 消"); // NON-NLS-1 //$NON-NLS-1$
		// Configure layout data
		GridData data = new GridData(SWT.NONE, SWT.NONE, false, false);
		data.widthHint = F_BUTTON_WIDTH_HINT;
		data.verticalIndent = 10;
		btn_cancel.setLayoutData(data);
	}

	/**
	 * 
	 */
	private void createUIButtonOK() {
		// Create the button
		btn_ok = new Button(comp_Login, SWT.PUSH);
		btn_ok.setText("登 录"); // NON-NLS-1 //$NON-NLS-1$
		// Configure layout data
		GridData data = new GridData(SWT.NONE, SWT.NONE, false, false);
		data.widthHint = F_BUTTON_WIDTH_HINT;
		data.verticalIndent = 10;
		btn_ok.setLayoutData(data);
	}

	/**
	 * 
	 */
	private void createUILabelBlank() {
		Label label = new Label(comp_Login, SWT.NONE);
		label.setVisible(false);
	}

	private void createUILabelTip() {
		GridData data = new GridData();
		data.horizontalIndent = F_LABEL_HORIZONTAL_INDENT;
		data.horizontalSpan = F_COLUMN_COUNT;

		lab_tip = new Label(comp_Login, SWT.NONE);
		lab_tip.setText("请输入工号和密码："); //$NON-NLS-1$
		lab_tip.setLayoutData(data);

		GridData data_hidden = new GridData();
		data_hidden.horizontalSpan = F_COLUMN_COUNT;

		Label lab_hidden = new Label(comp_Login, SWT.NONE);
		lab_hidden.setLayoutData(data_hidden);
		lab_hidden.setVisible(false);
	}

	/**
	 * 
	 */
	private void createUITextPassword() {
		// Create the text widget
		int style = SWT.PASSWORD | SWT.BORDER;
		txt_fpassword = new Text(comp_Login, style);
		// Configure layout data
		GridData data = new GridData(SWT.NONE, SWT.NONE, false, false);
		data.widthHint = F_TEXT_WIDTH_HINT;
		data.horizontalSpan = 3;
		txt_fpassword.setLayoutData(data);

		txt_fpassword.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub

			}

			public void keyReleased(KeyEvent e) {
				if (e.character == SWT.CR || e.keyCode == SWT.CR) {
					if (txt_fpassword.getText() == null
							&& txt_fpassword.getText().trim().length() <= 0) {
						lab_tip.setForeground(Display.getDefault()
								.getSystemColor(SWT.COLOR_RED));
						lab_tip.setText("密码不能为空！"); //$NON-NLS-1$
						txt_fpassword.setFocus();
						return;
					}
					handleButtonOKWidgetSelected();
					txt_fpassword.setFocus();
				}
			}

		});
	}

	/**
	 * 
	 */
	private void createUILabelPassword() {
		// Create the label
		Label label = new Label(comp_Login, SWT.NONE);
		label.setText("密 码:"); // NON-NLS-1 //$NON-NLS-1$
		// Configure layout data
		GridData data = new GridData();
		data.horizontalIndent = F_LABEL_HORIZONTAL_INDENT;
		label.setLayoutData(data);
	}

	/**
	 * 
	 */
	private void createUITextUserName() {
		// Create the text widget
		txt_fusername = new Text(comp_Login, SWT.BORDER);
		// Configure layout data
		GridData data = new GridData(SWT.NONE, SWT.NONE, false, false);
		data.widthHint = F_TEXT_WIDTH_HINT;
		data.horizontalSpan = 3;
		txt_fusername.setLayoutData(data);
		txt_fusername.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub

			}

			public void keyReleased(KeyEvent e) {
				if (e.character == SWT.CR || e.keyCode == SWT.CR) {
					if (Assert.isNull(txt_fusername.getText())) {
						lab_tip.setForeground(Display.getDefault()
								.getSystemColor(SWT.COLOR_RED));
						lab_tip.setText("工号不能为空！");
						txt_fusername.setFocus();
						return;
					}
					setUserNameByGh(txt_fusername.getText());
				}
			}
		});

		txt_fusername.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent e) {
				if (Assert.isNull(txt_fusername.getText())) {
					lab_tip.setForeground(Display.getDefault().getSystemColor(
							SWT.COLOR_RED));
					lab_tip.setText("工号不能为空！");
					txt_fusername.setFocus();
					return;
				}
				setUserNameByGh(txt_fusername.getText());
			}
		});
	}

	/**
	 * 根据用户名取登陆名
	 * 
	 * @param gh
	 */
	private void setUserNameByGh(String gh) {
		try{
		 TuserInfo userinfo = DataSource.oasidiService.getUserInfo(gh);
		 if(userinfo!=null && userinfo.getFusername()!=null){
			 lab_tip.setText("");
			 txt_name.setText(userinfo.getFusername());
			 txt_fpassword.setFocus();
			 txt_name.setForeground(Display.getDefault()
						.getSystemColor(SWT.COLOR_DARK_GREEN));
		 }else{
			 lab_tip.setForeground(Display.getDefault()
						.getSystemColor(SWT.COLOR_RED));
			 lab_tip.setText("用户名错误!");
			 txt_fusername.setFocus();
			 txt_name.setText("");
			 return;
		 }
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	private void createUILabelUserName() {
		// Create the label
		Label label = new Label(comp_Login, SWT.NONE);
		label.setText("工 号："); // NON-NLS-1 //$NON-NLS-1$
		// Configure layout data
		GridData data = new GridData();
		data.horizontalIndent = F_LABEL_HORIZONTAL_INDENT;
		label.setLayoutData(data);
	}

	/**
	 * 
	 */
	private void createUICompositeBlank() {
		Composite spanner = new Composite(comp_Login, SWT.NONE);
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.horizontalSpan = F_COLUMN_COUNT;
		spanner.setLayoutData(data);
	}

	/**
	 * 
	 */
	private void createUICompositeLogin() {
		comp_root = new Composite(parent, SWT.NONE);
		comp_root.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

		stackLayout = new StackLayout();
		comp_root.setLayout(stackLayout);

		comp_Login = new Composite(comp_root, SWT.NONE);
		GridLayout layout = new GridLayout(F_COLUMN_COUNT, false);
		comp_Login.setLayout(layout);

		comp_blank = new Composite(comp_root, SWT.NONE);
		comp_blank.setLayout(new GridLayout());

		stackLayout.topControl = comp_Login;

		progressBar = new ProgressBar(parent, SWT.NONE);
		progressBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false));
		progressBar.setVisible(false);

	}

	private void configureUISplash() {
		GridLayout layout = new GridLayout();
		layout.horizontalSpacing = 0;
		layout.verticalSpacing = 0;
		parent.setLayout(layout);
		parent.setBackgroundMode(SWT.INHERIT_DEFAULT);
	}

	/**
	 * 判断是否完成
	 * 
	 * @return
	 */
	public boolean isFinished() {
		return isFinished;
	}

	public void setFinished(boolean isFinished) {
		this.isFinished = isFinished;
	}

}
